import React, { Component } from 'react';
import { Card, Table, Button, message } from 'antd';
import { connect } from 'dva';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import moment from 'moment';
import styles from './index.less';
import router from 'umi/router';
import * as G from '@/utils/common';
import PateoSearchForm from '@/components/common/PateoSearchForm';

const logTypeArr = [
  { value: 1, label: 'OMS提醒' },
  { value: 2, label: '告警提醒' },
  { value: 3, label: 'vin码冲突' },
  { value: 4, label: '诊断上报' },
  { value: 5, label: 'can网络异常' },
  { value: 6, label: 'E-CALL' },
  { value: 7, label: '三级告警' },
];
const mapStateToProps = (state: any) => ({
  connectPlat: state.connectPlat,
  menu: state.menu,
  loading: state.loading.models['connectPlat'],
});
class VehicleReportLogQuery extends Component<any, any> {
  state = {
    modalVisible: false,
    postUrl: '',
    extendStatus: false,
    formValues: {
      startTime: moment()
        .add(-1, 'week')
        .valueOf(),
      endTime: moment().valueOf(),
    },
    pagination: {
      pageNo: 1,
      pageSize: 10,
    },
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues, pagination } = this.state;

    this.unlisten = this.props.history.listen((location: any, action: any) => {
      const { sourcePage } = location;
      let values = {
        ...pagination
      }
      if ( sourcePage === 'vehicleReportLogDetail' ) {
        //  详情返回
        const tempValues = sessionStorage.getItem('vehicleReportLogQuerySearchValues')
        values = {
          ...values,
          ...(JSON.parse(tempValues) || {})
        }
        this.setState({
          extendStatus: true,
        })
      }

      const { pageNo, pageSize, ...rest } = values;
      this.setState({
        formValues: {
          ...formValues,
          ...rest,
        },
        pagination: {
          pageNo,
          pageSize
        }
      }, () => {
        const { formValues, pagination } = this.state
        this.searchForm.current.setFieldsValue({
          ...formValues,
          handleTimeRange: [moment(formValues.startTime), moment(formValues.endTime)],
        });
        dispatch({
          type: 'connectPlat/queryList',
          payload: { ...formValues, ...pagination },
        });
      })
    })
  }

  componentWillUnmount() {
    if(this.unlisten) {
      this.unlisten();
    }
  }

  handleFreshPage = () => {
    const {
      connectPlat: {
        connectReportLog: { pagination },
      },
      dispatch,
    } = this.props;
    const { current, pageSize } = pagination;
    let params = { pageNo: current, pageSize: pageSize };
    dispatch({
      type: 'connectPlat/queryList',
      payload: { ...params },
    });
  };
  /**
   * 参数校验&分页入参处理
   * @param fieldsValue
   */
  handleFieldsValue = (fields: any) => {
    const {
      connectPlat: {
        connectReportLog: { pagination },
      },
    } = this.props;
    const { current, pageSize } = pagination;
    if (G.isNotEmptyAndNil(fields['handleTimeRange'])) {
      const [start, end] = fields.handleTimeRange;
      fields['startTime'] = moment(start).valueOf();
      fields['endTime'] = moment(end).valueOf();
      fields['pageNo'] = 1;
      fields['pageSize'] = pageSize;
      delete fields['handleTimeRange'];
      !fields['vin'] && delete fields['vin'];
      // if (moment(fields.startTime).isBefore(moment(fields.endTime).subtract(1, 'months'))) {
      //   message.warning('操作时间区间为一个月！');
      //   return false;
      // } else {
      return fields;
      // }
    } else {
      message.warning('请选择发送时间！');
      return false;
    }
  };
  handleFormReset = () => {
    let startTime = moment()
      .add(-1, 'week')
      .valueOf();
    let endTime = moment().valueOf();
    this.searchForm.current?.resetFields();
    this.searchForm.current.setFieldsValue({
      handleTimeRange: [moment(startTime), moment(endTime)],
      // vin: null,
    });
    this.setState({
      formValues: {
        startTime: startTime,
        endTime: endTime,
      },
      pagination: {
        pageNo: 1,
        pageSize: 10,
      },
    });
  };
  // 分页时触发
  tableOnChange = (pagination: any) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    // const current = pagination.current;
    const { current, pageSize } = pagination
    const params = {
      ...formValues,
      pageNo: current,
      pageSize:pageSize,
    };
    this.setState({
      pagination: {
        pageNo: current,
        pageSize: pageSize
      }
    }, () => {
      dispatch({
        type: 'connectPlat/queryList',
        payload: { ...params },
      });
    })
  };

  render() {
    const {
      location: { pathname = '/' },
      loading,
      connectPlat: {
        connectReportLog: { logList = [], pagination },
      },
    } = this.props;

    const { formValues, extendStatus } = this.state;
    const columns: Array<any> = [
      {
        title: 'VIN码',
        dataIndex: 'vin',
      },
      {
        title: '上报类型',
        dataIndex: 'reportType',
        render: (text: any) => {
          return logTypeArr.find(item => item.value == text)?.label;
        },
      },
      {
        title: '协议版本号',
        dataIndex: 'protocolVersion',
      },
      {
        title: '消息ID',
        dataIndex: 'messageId',
      },
      {
        title: '服务类型',
        dataIndex: 'serviceType',
      },
      {
        title: '消息发送时间',
        dataIndex: 'messageSendTime',
        render: (text: any) => {
          return moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '消息版本号',
        dataIndex: 'messageVersion',
      },
      {
        title: '数据长度',
        dataIndex: 'dataLength',
      },
      {
        title: '操作',
        dataIndex: '操作',
        key: 'opt',
        width: 150,
        render: (text: any, data: any) => {
          const btns = [
            {
              title: '详情',
              key: 'detail',
              auth: 'connectReportLogDetail_show',
              onConfirm: (e: any) => {
                e.stopPropagation();
                const { formValues, pagination } = this.state;
                const searchValues = {
                  ...formValues,
                  ...pagination
                }
                sessionStorage.setItem('vehicleReportLogQuerySearchValues', JSON.stringify(searchValues));
                sessionStorage.setItem('vehicleReportLogData', JSON.stringify(data));
                router.push('/connectPlat/vehicleReportLogQuery/vehicleReportLogDetail');
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        title: '发送时间',
        type: 'rangePicker',
        key: 'handleTimeRange',
        customStyle: 10,
        initialValue: [moment(formValues.startTime), moment(formValues.endTime)],
        rules: [{ required: true, message: '发送时间必选!' }],
      },
      {
        type: 'input',
        title: 'VIN码',
        key: 'vin',
        customStyle: 6,
        rules: [
          {
            required: false,
            message: '请输入10-17的英文和数字',
            min: 10,
            max: 17,
            pattern: '^[a-zA-Z0-9]*$',
          },
        ],
      },
      {
        title: '上报类型',
        type: 'select',
        customStyle: 6,
        selectOptions: logTypeArr,
        key: 'reportType',
      },
    ];
    return (
      <div className={styles.container}>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            isExtend={extendStatus}
            fetchParams={{ type: 'connectPlat/queryList' }}
            saveFormValues={(val: any) =>
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.handleFieldsValue}
          />
        </Card>
        <Card title="" bordered={false}>
          <Table
            className={styles['customer-grid']}
            loading={loading}
            rowKey={row => row.id}
            columns={columns}
            size="small"
            pagination={paginationProps}
            dataSource={logList}
            onChange={this.tableOnChange}
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(VehicleReportLogQuery);
